(:
  A procedure to select the contents of the "chat" interventions
:)
declare boundary-space strip;
import module namespace
    jj = "http://kumquat.emse.fr/utilitaires"
    at "jjutils.xq" ;

declare function local:get-time-milli ($item as element()) as xs:integer 
		{
			xs:integer($item/info[@name="time"]/time/date)
		};

<display>{
let $maxdelta := if ($arguments[2]) then xs:integer($arguments[2]) * 1000 else 60000
let $t := $arguments[1]
let $d := doc($t)/display/item
let $myitems := 
	for $e at $p in $d
	let $prev := $e/preceding-sibling::item[1]
	let $succ := $e/following-sibling::item[1]
	let $now := local:get-time-milli($e)
	let $prevtime := if (fn:empty($prev)) then 
		0 else 
		local:get-time-milli($prev)
	let $succtime := if (fn:empty($succ))
		then $now + 2 * $maxdelta
		else local:get-time-milli($succ)
	where   $now - $prevtime gt $maxdelta or
			$succtime - $now gt $maxdelta	
	return 
	<item>{
		<info name="type">{
			if (($now - $prevtime) gt $maxdelta)
	 		then "textboard-begin-write"
	 		else "textboard-end-write"
	    }</info>,
		for $info in $e/info[@name!="type"]
		return $info
	}</item>
for $e at $p in $myitems			
let $isbegin := $e/info[@name="type"]="textboard-begin-write"
let $succ := $myitems[$p+1]
let $until := if (fn:empty($succ))
	then ""
	else jj:formatMMMSS(local:get-time-milli($succ) - local:get-time-milli($e))
return
<item>{
	$e/info[@name="type"],
    $e/info[@name="time"],
    $e/info[@name="src-anchor"],
    $e/info[@name="user"],
    $e/info[@name="currenttext"],
    $e/info[@name="room"],
    <info name="content">{
		if ($isbegin)
		then <text color="blue">{
			fn:concat("begin editing block. ",
			$until, 
			if (fn:empty($succ)) then ()
				else fn:concat(" until next ",$maxdelta idiv 1000,"s break"))
		}</text>
		else <text color="red">{
			"end editing block. ",
			$until,
			if (fn:empty($succ)) then ()
				else (" until next writing block") 
		}</text>
	}</info>
}</item>
}</display>
